import { getToken, setToken } from '@/utils/auth'
import { sysLogin, sysProfile, sysUser } from '@/api/user'
import { asyncRoutes, constantRoutes } from '@/router/index'
import router from '@/router/index'
import { resetRouter } from '@/router/index'
const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  // 清除token与userInfo,重置路由(解决切换账号时上一账号的路由信息没有销毁重置)
  logout(state) {
    state.userInfo = ''
    state.token = ''
    setToken('')
    resetRouter()
  }
}
const actions = {
  async toLogin(store, value) {
    // 在 vuex 中调用api
    const res = await sysLogin(value)
    store.commit('setToken', res.data)
  },
  // 获得用户信息
  async getUserInfo({ commit }) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    // 合并对象
    const res3 = Object.assign({}, res.data, res2.data)
    // 用户权限数据: res3.roles.menus
    // 动态路由数据:asyncRoutes
    const newArr = asyncRoutes.filter((item) => {
      return res3.roles.menus.includes(item.meta.name)
    })
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    router.addRoutes(newArr)
    commit('router/setRouter', [...constantRoutes, ...newArr], { root: true })
    // 路由动态添加的坑点:
    //  1.通过动态路由添加的路由不能立马使用,需要再经历一次beforEach
    //    解决方式: next(to.fullPath)
    //  2.因为通过动态添加的路由不能立马使用,但是静态路由中包含404的匹配,它会直接匹配到404去
    //    解决方式: 将404匹配的路由通过addRoutes添加就没问题了
    console.log('匹配的路由项', newArr)
    commit('setUserInfo', res3)
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
